import { _decorator, Button, Color, Component, find, instantiate, Label, Material, Node, Prefab, resources, size, Sprite, SpriteFrame, Vec2, Vec3 } from 'cc';
import { num } from './components/num';
import { get, post } from '../utils/request';

const { ccclass, property } = _decorator;


const cellSize = 100; // 每个按钮的大小
const spacing = 20; // 按钮之间的间距

@ccclass('game_js')
export class game_js extends Component {

    @property
    private score: number = 0; // 当前得分
    @property
    private state: number = 0; // 状态： 0 未开始， 1 记数字， 2 答题

    @property
    private round: number = 1; // 第一关

    @property
    private level: number = 1; // 难度级别

    @property
    private answers: Set<number | unknown> = new Set(); // 答案

    @property
    private selectItems: Set<number | unknown> = new Set();// 用户选中的数组

    @property
    private titleNode: Node = null;

    @property
    private resultPop: any = null; // 成功的弹窗

    @property
    private failPop: any = null; // 失败的弹窗



    @property
    public startNode: Node = null;
    @property
    public readNode: Node = null;

    @property
    public sureBtn: Node = null; // 确定按钮

    @property
    public numberWrap: Array<Node> = [];




    start() {
        // this.startNode = this.node.getChildByName("start");
        // this.readNode = this.node.getChildByName("readNumber");
        // this.titleNode = this.node.getChildByName("title");
        // this.resultPop = this.node.getChildByName("resultPop");
        // this.failPop = this.node.getChildByName("failPop");
        // this.sureBtn = this.node.getChildByName("sureBtn");
        // this.numberWrap = find("numbers", this.readNode);
        // this.startNode.active = true;
        // 获取用户得分
        this.getUserScore();
            console.log(99);
    }

    update(deltaTime: number) {

    }

    getUserScore() {
        post("/c_game/getUserScore", {
            gameId: "memory"
        }).then(res => {
            console.log(res);
            // this.userScore = res.data.score;
            // this.numberWrap.getComponent(number).setNumber(this.userScore);
        })
    }
    /**
     * 点击开始游戏
     */
    onClick() {
        console.log("click");
        // this.startNode.active = false;
        // this.readNode.active = true;
        this.startRead();
    }

    private async loadButtonPrefab() {
        return new Promise((resolve, reject) => {
            resources.load("prefab/Button", Prefab, (err, prefab) => {
                if (err) {
                    reject(null);
                    return console.error("加载Prefab失败");
                }
                resolve(prefab);
            });
        })

    }
    /**
     * 获取随机数
     * @param min 
     * @param max 
     * @returns 
     */
    getRamdomNumber(min, max) {
        return min + Math.floor(Math.random() * max);
    }

    /**
     * 获取多个随机数
     * @param min 
     * @param max 
     * @param count 
     * @returns 
     */
    getRamdomNumbers(min, max, count) {
        let arr = new Set();

        // for (let i = 0; i < count; i++) {
        //     arr.add(this.getRamdomNumber(min, max));
        // }
        // TODO: 这里处理数字重复的问题
        while (arr.size < count) {
            arr.add(this.getRamdomNumber(min, max));
        }
        return arr;
    }


    /**
     * 在页面上显示数字
     */
    async createNumbers(gridSize, numberArr, enable) {
        const prefab = await this.loadButtonPrefab();
        const arr = this.shuffleArray(numberArr);
        // 定义25宫格的位置
        const totalWidth = gridSize * cellSize + (gridSize - 1) * spacing;
        const totalHeight = gridSize * cellSize + (gridSize - 1) * spacing;
        const halfWidth = totalWidth / 2;
        const halfHeight = totalHeight / 2;
        let i = 0;

        for (let col = 0; col < gridSize; col++) {
            for (let row = 0; row < gridSize; row++) {
                i++;
                // 计算按钮的位置
                const x = -(halfWidth - col * (cellSize + spacing)) + cellSize / 2;
                const y = -(halfHeight - row * (cellSize + spacing)) + cellSize / 2;
                const button = instantiate(prefab); // 假设你已经有一个预制体(buttonPrefab)
                button.getComponent(Button).interactable = enable; // 设置按钮可交互
                // 设置按钮的文本
                const label = button.getComponentInChildren(Label);

                // 设置按钮的位置
                const position = new Vec3(x, y);
                button.setPosition(position);
                let currentNum = arr[i - 1];
                label.string = currentNum;
                // 添加点击事件处理函数
                button.on(Button.EventType.CLICK, () => {
                    console.log(`Button ${currentNum} clicked`);
                    // 判断是否
                    if (this.selectItems.has(currentNum)) {
                        this.selectItems.delete(currentNum);
                    } else {
                        this.selectItems.add(currentNum);
                    }
                    if (this.selectItems.size <= this.answers.size) {
                        this.updateClicked();
                    }
                    // this.checkAnswer(currentNum);
                    this.sureBtn.active = this.selectItems.size > 0;

                    // this.loadSpriteFrame().then((spriteFrame) => {
                    //     button.getComponent(Button).normalSprite = spriteFrame;
                    // })
                });

                // 将按钮添加到父节点
                this.numberWrap.addChild(button);
            }
        }

    }

    updateClicked() {
        const buttons = this.numberWrap.children;
        for (let btn of buttons) {
            const label = btn.getComponentInChildren(Label);
            const value = Number(label.string);
            if (this.selectItems.has(value)) {
                label.color = new Color(255, 0, 0);
            } else if (this.selectItems.size >= this.answers.size) {
                label.color = new Color(66, 66, 66);
                btn.getComponent(Button).interactable = false;
            } else {
                btn.getComponent(Button).interactable = true;
                label.color = new Color(0, 0, 0);
            }
        }
    }
    /**
     * 检查答案是否正确
     * @param num 
     */
    checkAnswer(num) {
        console.log(`添加数字:${num}, 当前选中数字:${this.selectItems}`);

        if (this.selectItems.size == this.answers.size) {
            let result = true;
            if (this.selectItems.size !== this.answers.size) {
                result = false;
            } else {
                for (let element of this.selectItems) {
                    if (!this.answers.has(element)) {
                        result = false;
                    }
                }
            }
            console.log("检测结果：", result);
            this.updateUserScore();

            if (result) {
                this.score += 1;
                this.round += 1;
                this.level += 1;
                this.resultPop.active = true;
            } else {
                this.failPop.active = true;
            }
            this.sureBtn.active = false;
            // this.resetGame(result);
        }


    }
    /**
     * 更新世界分数
     */
    updateUserScore() {
        console.log("上报用户得分：", this.score);
    }

    /**
     * 重置游戏
     */
    resetGame() {

        // 移除所有数字
        const numberWrap = find("numbers", this.readNode);
        numberWrap.removeAllChildren();
        // 重新开始
        // this.readNode.active = true;
        this.startRead();
    }
    private async loadSpriteFrame() {
        return new Promise((resolve, reject) => {
            resources.load("images/Sprite", SpriteFrame, (err, spriteFrame) => {
                if (err) {
                    reject(null);
                    return console.error("加载SpriteFrame失败");
                }
                resolve(spriteFrame);
            });
        })

    }

    /**
     * 随机打乱数组顺序
     * @param array 
     * @returns 
     */
    shuffleArray(array) {
        // 创建一个副本，避免修改原数组
        let shuffledArray = array.slice();

        // Fisher-Yates 洗牌算法
        for (let i = shuffledArray.length - 1; i > 0; i--) {
            // 随机选择一个索引 j，范围 [0, i]
            const j = Math.floor(Math.random() * (i + 1));

            // 交换元素
            [shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]];
        }

        return shuffledArray;
    }
    /**
     * 开始读数字倒计时
     */
    startRead() {
        console.log("startRead");
        this.startNode.active = false;
        this.answers = new Set();
        this.selectItems = new Set();
        this.resultPop.active = false;
        this.failPop.active = false;

        // 获取2个随机数
        this.answers = this.getRamdomNumbers(10, 100, this.level * this.level);
        console.log("当前答案：", this.answers);
        // 产生数字
        this.createNumbers(this.level, Array.from(this.answers), false);

        let reaminTime = 5;
        const remainNode = find("remain", this.readNode).getComponent(Label);
        remainNode.node.active = true;
        remainNode.string = `倒计时：${reaminTime--}s`;
        this.schedule(() => {
            remainNode.string = `倒计时：${reaminTime--}s`;
            // this.remainNode.getComponent(Label).string = reaminTime-- + "";
            if (reaminTime <= 0) {
                this.unscheduleAllCallbacks();
                remainNode.node.active = false;
                // 开始进入答题模式
                this.startAnswer();
            }
        }, 1);
    }

    /**
     * 开始答题
     */
    startAnswer() {
        this.state = 2; // 答题阶段
        // 先移除所有子节点
        const numberWrap = find("numbers", this.readNode);
        numberWrap.removeAllChildren();

        const level = this.level + 1;
        const opts = this.getRamdomNumbers(10, 100, level * level);
        const options = [...this.answers, ...opts];
        this.createNumbers(level, options, true);
        find("title", this.readNode).getComponent(Label).string = "请选择您刚刚看到的数字";
    }

}

